<template>
    <div class="content_panel project_modules">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('pageTitle.financeLedger')}}</span> <!--财务平账-->
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item prop="innerOrderId" label=""> <!--内部订单号-->
                            <el-input v-model="form.innerOrderId" :placeholder= "$t('common.innerOrderId')" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                     <el-col :span="4">
                        <el-form-item prop="mobileNumber" label=""> <!--手机号-->
                            <el-input v-model="form.userPhone" :placeholder= "$t('common.mobileNumber')" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="contractNumber" label=""><!--还款序列号-->
                            <el-input v-model="form.contractNumber" :placeholder="$t('common.repaySerialNumber')" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- 伪名 -->
                    <el-col :span="4">
                        <el-form-item prop="whiteProductName" v-if="domain == 'Bene'"> <!---->
                            <el-input v-model="form.whiteProductName" :placeholder="$t('common.productName')" clearable><!----></el-input>
                        </el-form-item>
                        <el-form-item v-else prop="kana"> <!--姓名-->
                            <select-kana-list v-model="form.kana" :multiple="false" :placeholder="$t('finance.pseudonym')"></select-kana-list><!--app名称-->
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item>
                            <el-button @click="search" icon="el-icon-search" type="primary">{{ $t('common.search') }}</el-button>
                            <el-button v-if="showBatch" @click="showLedgerDialog=true" type="primary">{{ $t('finance.batchFinanceLedger') }}</el-button><!--批量平账-->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form><!--el-form end-->
        </div><!--content_panel_top-->
        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table :data="tableData" style="width: 100%;" :highlight-current-row="true" :max-height="tableMaxHeight">
                        <el-table-column :label="$t('common.innerOrderId')"  prop="orderId" min-width="150"></el-table-column><!--内部订单号-->
                        <el-table-column :label="$t('system.appName')" prop="appName" min-width="130"></el-table-column><!--APP名称-->
                        <el-table-column v-if="domain=='Bene'" :label="$t('finance.productName')" prop="whiteProductName" min-width="130"></el-table-column><!--伪名-->
                        <el-table-column v-else :label="$t('finance.pseudonym')" prop="kana" min-width="130"></el-table-column><!--伪名-->

                        <el-table-column :label="$t('common.mobileNumber')" prop="userPhone" width="150"></el-table-column><!--手机号码-->
                        <el-table-column :label="$t('common.dateRepayment')" prop="repayTime" width="200">
                            <template slot-scope="{ row }">{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column><!--应还日期-->
                        <el-table-column :label="$t('common.repaySerialNumber')" prop="contractNumber" min-width="170"></el-table-column><!--还款序列号-->
                        <el-table-column :label="$t('common.contractAmount')" prop="contractAmount" min-width="120">
                            <template slot-scope="{ row }">{{ row.contractAmount | formatCurrency }}</template><!--合同金额-->
                        </el-table-column>

                        <el-table-column :label="$t('common.loanRate')" prop="loanInterest" width="100">
                            <template slot-scope="{ row }">{{ row.loanInterest | formatCurrency }}</template><!--利息-->
                        </el-table-column>

                        <el-table-column :label="$t('common.penaltyRate')" prop="lateCharge" width="100">
                            <template slot-scope="{ row }">{{ row.lateCharge | formatCurrency }}</template><!--罚息-->
                        </el-table-column>

                        <el-table-column :label="$t('common.restRepay')" prop="restRepay" min-width="120"><!--挂帐金额-->
                            <template slot-scope="{ row }">{{ row.restRepay | formatCurrency }}</template>
                        </el-table-column>

                        <el-table-column :label="$t('finance.ledgerMoney')" prop="allSettleAmount" min-width="120"><!--已平账金额-->
                            <template slot-scope="{ row }">{{ row.allSettleAmount| formatCurrency }}</template>
                        </el-table-column>

                         <el-table-column :label="$t('common.operation')" prop="operation" width="200">
                             <template slot-scope="scope">
                                <el-button @click="showModal(scope.row)" class="btn" type="text" size="small">{{ $t('finance.ledger') }}</el-button><!--编辑资源-->
                            </template>
                        </el-table-column><!--操作-->

                    </el-table>
                    <!--分页组件-->
                    <pagination @pageChange="pageChange" :page="page"></pagination>
                </div><!--module_content-->
            </div>
        </div><!--module_content-->
        <!-- 平账 -->
        <el-dialog :title="$t('pageTitle.financeLedger')" :visible.sync="dialogVisible" width="500px">
            <el-form :model="formApplyCorrection" :inline="false" class="module_form">
                <el-form-item :label="$t('common.innerOrderId') + ':'" :label-width="formLabelWidth"><!--内部订单号-->
                    {{formApplyCorrection.innerOrderId}}
                </el-form-item>
                <el-form-item :label="$t('common.restRepay') + ':'" :label-width="formLabelWidth"><!--挂账金额-->
                   <el-col :span="8">
                        {{formApplyCorrection.restRepay}}
                   </el-col>
                </el-form-item>
                <el-form-item :label="$t('common.penaltyInterest') + ':'" :label-width="formLabelWidth"><!--罚息-->
                    {{formApplyCorrection.penaltyInterest}}
                </el-form-item>

                <el-form-item :label="$t('finance.amountPublicTransfer' ) + ':'" :label-width="formLabelWidth"><!--对公转账金额-->
                     <el-input-number
                     :precision="2"
                     :controls="checkParam.enlControls"
                     controls-position="right"
                     :max="checkParam.amountPublicTransfer"
                     :min="checkParam.minMoney"
                     v-model="formApplyCorrection.amountPublicTransfer"
                     :placeholder= "$t('finance.amountPublicTransfer')" clearable
                     />
                </el-form-item>

                <el-form-item :label="$t('finance.freePenaltyInterest') + ':'" :label-width="formLabelWidth"><!--免罚息金额-->
                   <el-input-number
                   :precision="2"
                   :max="checkParam.penaltyInterest"
                   :min="checkParam.minMoney"
                   :controls="checkParam.enlControls"
                   controls-position="right"
                   v-model="formApplyCorrection.freePenaltyInterest"
                   :placeholder= "$t('finance.freePenaltyInterest')"
                   clearable
                   />
                </el-form-item>
                
                <el-form-item :label="$t('common.remark') + ':'" :label-width="formLabelWidth"><!--备注-->
                <el-checkbox v-model="isChecked" @change="changeChecked">{{$t('common.clientCancel')}}</el-checkbox>
                  <el-input
                    type="textarea"
                    v-model="formApplyCorrection.remark"
                    :rows="5"
                    :maxlength="200"
                    :disabled="isChecked"
                    />

                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
                <el-button type="primary" @click="submitLedger">{{ $t('common.confirm') }}</el-button>
            </div>
        </el-dialog>
        <!-- 平账 -->

        <!--批量平账start-->
        <upload-finance-file
            :title="$t('finance.batchFinanceLedger')"
            :visible.sync="showLedgerDialog"
            @submitUpload="batchSubmitLedger"
            :template-url="templateUrl">
        </upload-finance-file>
        <!--批量平账end-->
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import {keyMap} from '@/config';
    import SelectAppList from '@/components/select-app-list';
    import UploadFinanceFile from '@/components/upload-finance-file';
    import SelectKanaList from '@/components/select-kana-list';

    export default {
        name: 'repayNotRepay',
        components: {
            Pagination,
            SelectAppList,
            UploadFinanceFile,
            SelectKanaList
        },
        mixins: [mixin],
        data() {
            return {
                domain:'',
                isChecked:false,
                form: {
                    orderId: '',
                    userPhone: '',
                    contractNumber: '',
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                    status: '',
                },
                rules: {
                    orderId: [],
                    userPhone: []
                },
                overdueType: keyMap.overdueType,
                keyMap,
                formApplyCorrection: {
                    name: '',
                    orderId: '',
                    restRepay: '',
                    correctReason: this.$t('finance.errorOverdueCorrection'),
                    remark: ''
                },
                dialogVisible: false,
                formLabelWidth: "150px",
                checkParam:{
                    enlControls: false,
                    minMoney: 0,
                    penaltyInterest: 0,
                    amountPublicTransfer: 0
                },
                showLedgerDialog: false, // 显示批量平账弹框
                templateUrl: '/finance-ledger.xlsx', // 上传文件模板地址
            };
        },
        computed: {
            showBatch () {
                // 是否显示批量平账按钮
                return this.$store.getters.checkUserAuthority('finance.remit.finance-ledger.batch-finance-ledger');
            },
        },
        methods: {
            changeChecked(val){
                console.warn(val,'saas')
                if(val){
                    this.formApplyCorrection.remark = this.$t('common.clientCancel')
                }else{
                    this.formApplyCorrection.remark = ''
                }
            },
            getTableData(page = this.page) {
                const params = this.fillParams(page);
                this.$api.finance.repay.unRepayList(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                    }
                });
            },
            search() {
                this.page.currentPage = 1;
                this.getTableData();
            },
            // 打开模态框 传递数据
            showModal(row){
                this.dialogVisible = true;
                this.isChecked = false;
                this.formApplyCorrection.innerOrderId = row.orderId;
                this.formApplyCorrection.restRepay = row.restRepay;
                this.formApplyCorrection.penaltyInterest = Number(row.allCanSettleChargeAmount);
                // 初始化可输入值
                this.formApplyCorrection.freePenaltyInterest = 0 ;
                this.formApplyCorrection.amountPublicTransfer = 0 ;
                this.formApplyCorrection.remark = '';
                // 验证最大最小赋值
                this.checkParam.penaltyInterest = Number(this.formApplyCorrection.penaltyInterest);
                this.checkParam.amountPublicTransfer = Number(row.restRepay);
            },
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    orderId: form.innerOrderId,
                    userPhone: '',
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                    status: '',
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
                Object.keys(form).forEach(key => {
                    if (typeof form[key] === 'string' && form[key] && form[key]) {
                        form[key] = form[key].trim();
                        params[key] = form[key];
                    }
                });

                return params;
            },
            applyCorrection(row) {
                this.dialogApplyCorrection = true;
                this.formApplyCorrection = Object.assign({
                    name: '',
                    orderId: '',
                    correctDay: '',
                    correctReason: this.$t('finance.errorOverdueCorrection')
                }, row);

            },
            // 模态框提交按钮
            submitLedger() {

                let params = {
                    orderId: this.formApplyCorrection.innerOrderId,
                    normalTransferAmount: this.formApplyCorrection.amountPublicTransfer,
                    settleChargeAmount: this.formApplyCorrection.freePenaltyInterest,
                    remark: this.formApplyCorrection.remark
                }
                if(!params.normalTransferAmount  && !params.settleChargeAmount ){
                    this.$message.error(this.$tc('finance.ledgerError1'));
                    return;
                }
                if(params.normalTransferAmount == 0 && params == 0){
                    this.$message.error(this.$tc('finance.ledgerError1'));
                    return;
                }
                // 判断金额大小 对公转账金额+免罚息金额 > 挂账金额
                if(params.normalTransferAmount+params.settleChargeAmount > this.formApplyCorrection.restRepay){
                    this.$message.error(this.$tc('finance.ledgerError2'));
                    return;
                }
                this.$api.finance.fianceLedger.doSettleBill(params).then(res => {
                    const {status, error} = res;
                    if ('1' === status && '00000000' === error) {
                        this.dialogVisible = false;
                        this.getTableData();
                    }
                });
            },
            // 批量提交平账
            batchSubmitLedger(file) {
                const params = new FormData();
                params.append('file', file);
                this.$api.finance.fianceLedger.doBatchSettleBill(params).then(res => {
                    const { status, data } = res;
                    if ('1' === status) {
                        // const me = this;
                        // <p>成功: {success}; 失败: {fail}</p><p>失败的订单号: {orderIds}</p>  批量平账
                        this.$alert(this.$t('finance.afterBatchFinanceLedger', { success: data.successOrdersCount, fail: data.failedOrdersCount, orderIds: data.failedOrders.join(', ') }), this.$t('finance.batchFinanceLedger'),{
                            dangerouslyUseHTMLString: true,
                            callback() {
                                // me.getTableData(); // 更新列表数据
                            }
                        });
                        this.showLedgerDialog = false;
                    }
                })
            },
        },
        created() {
            this.domain = this.$storage.get('user').domain
            // console.log('start');
            this.tableMaxHeight = document.body.clientHeight - 280;
            // this.getTableData();
        }
    }
</script>
<style lang="scss" scoped>
    .cursor-pointer {
        cursor: pointer;
    }
</style>
